var reduce = require('arr-reduce');
 
var ret = reduce([1, 2, 3, 4, 5], function (prev, curr) {
  return prev + curr;
});


console.log(ret)

var ret = arrayReduce([1, 2, 3, 4, 5], function (prev, curr) {
  return prev + curr;
});
console.log(ret)
console.log('-----------------------\n')

 
var ret = reduce([], function (prev, curr) {
  	return prev + curr;
});
console.log(ret)
var ret = arrayReduce([], function (prev, curr) {
  	return prev + curr;
});
console.log(ret)

console.log('-----------------------\n')

var ret = arrayReduce(['b', 'c'], function(prev, cur) {
	return prev.concat(cur)
}, ['a'])

console.log(ret)



/**
 * [arrayReduce description]
 * @param  {[type]}   arr      [description]
 * @param  {Function} callback [description]
 * @param  {[type]}   initVal  [description]
 * @return {[type]}            [description]
 */
function arrayReduce(arr, callback, initVal, thisArg) {

	if(!Array.isArray(arr)) {
		throw new TypeError('Excepts an array as the first argument')
	}
	var one , prev, i = 0;
	
	// 判断是否传递初始值
	if(initVal === undefined) {
		// if(arr.length === 0) throw new TypeError('Reduce of empty array with no initial value')
		prev = arr[0]
		i = 1
	} else {
		prev = initVal
	}

	for (; i < arr.length; i++) {
		prev = callback.call(thisArg, prev, arr[i], i, arr)
	}

	return prev
}

/**
 * [arrayReduceV2 description]
 * @param  {[type]}   arr      [description]
 * @param  {Function} callback [description]
 * @param  {[type]}   initVal  [description]
 * @param  {[type]}   thisArg  [description]
 * @return {[type]}            [description]
 */
function arrayReduceV2(arr, callback, initVal, thisArg) {
	var init = arguments.length > 2
	if(arr == null) {
		if(init) {
			return initVal
		} else {
			throw new TypeError('expects an array or initial value')
		}
	}

	if(!arr.length) {
		return initVal
	}

	var len = arr.length, prev = initVal
	for (var i = 0; i < len; i++) {
		if(!init) {
			prev = arr[i]
			init = true
		} else {
			prev = callback.call(thisArg, prev, arr[i], i, arr)
		}
	}

	return prev 
}